import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/pages/my_webview/my_webview_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';
import 'package:yysk_app/widget/verification_code_widet.dart';
import 'package:oktoast/oktoast.dart';

class SettingLogOff extends StatefulWidget {
  static const path = '/SettingLogOff';
  const SettingLogOff({super.key});
  @override
  State<StatefulWidget> createState() => _SettingLogOff();
}

class _SettingLogOff extends State<SettingLogOff> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController onePwdontroller = TextEditingController();
  final TextEditingController twoPwdController = TextEditingController();
  final registerEnable = false.obs;
  String pwdErrorOne = '';
  String pwdErrorTwo = '';
  String userAccount = '';
  int? smsId;
  String onePwd = '';
  String twoPwd = '';
  final GlobalController globalController = Get.find();
  var agree = false.obs;
  final TextEditingController passwordController = TextEditingController();
  String? password;
  final codes = RxString('');
  final id = Rx<int?>(0);
  final FocusNode focusNodeI = FocusNode();
  final FocusNode focusNodeV = FocusNode();
  final isFocusedI = false.obs;
  final isFocusedV = false.obs;

  @override
  void initState() {
    super.initState();
    //监听聚焦
    focusNodeI.addListener(() {
      isFocusedI.value = focusNodeI.hasFocus;
    });
    focusNodeV.addListener(() {
      isFocusedV.value = focusNodeV.hasFocus;
    });
  }

  @override
  void dispose() {
    super.dispose();
    focusNodeI.dispose();
    focusNodeV.dispose();
  }

  void _logoff() {
    http.netFetch(
      CommonApi.cancellation,
      params: {
        'smsId': id.value,
        'pwd': password,
        'codes': codes.value,
        'userAccount': globalController.user.value?.userTel,
      },
      success: (data) {
        showToast(data.data.toString());
        HiCache.getInstance().remove(LoginController.boardingPassToken);
        Get.offAllNamed(LoginPage.path);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    final GlobalController globalController = Get.find();
    final staticInfo = globalController.staticInfo.value;
    return Scaffold(
      backgroundColor: AppColors.backgroundColorBlack,
      bottomNavigationBar: BottomAppBar(
        padding: EdgeInsets.symmetric(horizontal: 24.px, vertical: 12.px),
        height: 112.px,
        color: Colors.transparent,
        child: Obx(() {
          return Column(
            children: [
              ButtonWidget(
                label: '注销',
                width: 327.px,
                height: 47.px,
                fontSize: 16,
                bgColorStart: AppColors.fontColorRed2,
                bgColorEnd: AppColors.fontColorRed2,
                fontColor: AppColors.fontColor,
                onPressed: () {
                  if (agree.value) {
                    _showSheet(context);
                  } else {
                    showToast('请阅读并同意《元宇时空账号注销协议》');
                  }
                },
              ),
              hiSpace(height: 12.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  CheckboxWidget(
                    onChanged: (v) => agree.value = v,
                    checked: agree.value,
                    size: 18.px,
                  ),
                  Text(
                    "我已阅读并同意",
                    style: TextStyle(
                      fontSize: 12.px,
                      color: AppColors.fontColorGray99,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Get.toNamed(
                        '${MyWebViewPage.path}?url=${Uri.encodeComponent(staticInfo?.logoutAgreement ?? '')}',
                        arguments: {
                          'url': Uri.encodeComponent(
                            staticInfo?.logoutAgreement ?? '',
                          ),
                        },
                      );
                    },
                    child: Text(
                      '《元宇时空账号注销协议》',
                      style: TextStyle(
                        color: AppColors.fontColorSearch,
                        fontSize: 12.px,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          );
        }),
      ),
      body: SingleChildScrollView(
        child: Obx(() {
          return Column(
            children: [
              SizedBox(height: top),
              CustomAppBar2(title: '注销账号', context: context),
              hiSpace(height: 29.px),
              ImageAssetWidget(
                imageUrl: 'static/images/log_off.png',
                width: 116.px,
                height: 116.px,
                radius: BorderRadius.circular(116.px),
                fit: BoxFit.fitWidth,
                alignment: Alignment.topCenter,
              ),
              hiSpace(height: 24.px),
              Text(
                '注销账号是不可逆操作',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 16,
                  color: AppColors.fontColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
              hiSpace(height: 22.px),
              Padding(
                padding: EdgeInsets.all(12.px),
                child: Container(
                  padding: EdgeInsets.all(14.px),
                  constraints: BoxConstraints(minWidth: context.width - 24.px),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12.px),
                    color: AppColors.backgroundColorBlackLight,
                  ),
                  child: HtmlWidget(
                    globalController.staticInfo.value?.logoutPageDescription ??
                        '',
                    textStyle: const TextStyle(
                      color: AppColors.fontColorGray99,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  void _showSheet(BuildContext context) {
    showConfirmDialog(
      context: context,
      message: '注销校验',
      children: [
        RichText(
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          text: TextSpan(
            children: <TextSpan>[
              TextSpan(
                text: '注销账号：',
                style: TextStyle(
                  color: AppColors.fontColorGray99,
                  fontSize: 12.px,
                ),
              ),
              TextSpan(
                text: globalController.user.value?.userTel ?? '--',
                style: TextStyle(color: AppColors.fontColor, fontSize: 12.px),
              ),
            ],
          ),
        ),
        hiSpace(height: 28.px),
        _codeLogin(),
        hiSpace(height: 24.px),
      ],
      actions: [
        ActionModel(
          label: '取消',
          onPressed: () {},
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
        ),
        ActionModel(
          label: '确认注销',
          colorStart: AppColors.fontColorRed2,
          colorEnd: AppColors.fontColorRed2,
          fontColor: AppColors.fontColor,
          onPressed: () {
            _logoff();
          },
        ),
      ],
    );
  }

  Widget _codeLogin() {
    return Column(
      children: [
        const SizedBox(height: 3),
        InputWidget(
          focusNode: focusNodeI,
          controller: passwordController,
          inputType: TextInputType.text,
          hint: '请输入登录密码',
          onChanged: (value) {
            setState(() {
              password = value.length > 18 ? value.substring(0, 18) : value;
            });
          },
          backgroundColor: AppColors.backgroundColorGreyF8,
          buttonRadio: 300,
        ),
        hiSpace(height: 8.px),
        VerificationCodeWidet(
          focusNode: focusNodeV,
          type: VerificationCodeType.LOGOUT,
          phoneNumber: globalController.user.value?.userTel ?? '',
          password: password,
          initialCount: 60,
          buttonRadio: 24,
          onChanged: _onCodeSubmit,
          hintText: '请输入验证码',
        ),
      ],
    );
  }

  _onCodeSubmit({String? code, int? msgId}) {
    if (code != null && code != '') {
      codes.value = code;
    }
    id.value = msgId!;
  }
}
